<template>
  <view class="media-player-page" v-if="episodeList.length > 0">
    <!-- 蒙层 -->
    <view v-if="isRecording" class="recording-mask" />
    <!-- 滑动选集页面 -->
    <swiper
      :class="showPopup ? 'myswiper' : ''"
      :vertical="true"
      :current="currentIndex"
      :duration="duration"
      easing-function="linear"
      @change="handleChangeVideo"
      :style="{ height: '100vh' }"
    >
      <swiper-item
        v-for="(item, index) in episodeList"
        :key="item.sort"
        :style="{ height: '100vh' }"
      >
        <view
          class="veplayer-page"
          v-if="Object.keys(episodeInfo).length !== 0"
        >
          <!-- 播放器 -->
          <MyVideo
            v-if="(isShowPayText !== 1 && sort == item.sort) && IsChangingEpisodeInfo === false"
            :idx="index"
            :sort="sort"
            :url="episodeInfo.file_url"
            :videoInfo="episodeInfo"
            ref="childRef"
            @updateEpisodeInfo="updateEpisodeInfo"
          >
          </MyVideo>

          <view class="pay-text" v-if="isShowPayText === 1 && AdBtnShow === false">
            该剧集为付费内容,完成支付即可观看~
          </view>
          
          <view v-if="isShowPayText === 1 && AdBtnShow"
            class="ad-tip-wrapper"
          >
            <text>看完广告才能解锁本集</text>
            <text>拍摄不易，感谢您支持一下哦</text>

            <text v-if="IsStopAdTimeout === true" style="margin-top: 40rpx; font-size: 32rpx;">点击屏幕继续解锁剧集</text>
          </view>
          <!-- <button class="ad-btn" type="primary" plain="true" v-if="isShowPayText === 1 && AdBtnShow"
            @click="handleAdClick"
          >
            看广告解锁剧集
          </button> -->

          <view class="ad-thumb-wrapper" v-if="isShowPayText === 1 && AdBtnShow && IsStopAdTimeout" 
          @click="AdTimeoutFunc"></view>

          <view class="ad-timeout-wrapper" v-if="isShowPayText === 1 && AdBtnShow && IsStopAdTimeout === false">
            <view class="ad-timeout-btn" @click="handleAdClick">{{ AdTimeoutNum }}s后看广告解锁剧集</view>
            <view class="ad-btn-close" @click="handleStopAdClick">×</view>
          </view>

          <!-- 侧边栏 -->
          <view class="sidebar" :class="isFull ? 'hidden' : ''">
            <view class="like">
              <image style="height: 66rpx;" mode="widthFix" :src="OSSImgUrl(`like-icon.png`)" />
              <view class="txt">19W</view>
            </view>

            <view class="collect" @click="setUserCollect">
              <image style="height: 68rpx;" mode="widthFix" :src="OSSImgUrl(`${ episodeInfo.is_collect === 0 ? 'collect-icon-default.png' : 'collect-icon.png' }`)" />
              <view class="txt">追剧</view>
            </view>

            <button open-type="share" class="share">
              <image style="height: 60rpx;" mode="widthFix" :src="OSSImgUrl(`share-icon.png`)" />
              <view class="txt">分享</view>
            </button>
          </view>


          <!-- 全屏按钮 -->
          <!-- <view class="full-screen" @click="isFull = !isFull">
            <text
              class="iconfont"
              :class="isFull ? 'icon-xiaoping02' : 'icon-quanping'"
            ></text>
          </view> -->

          <!-- 底部剧集名称 -->
          <view :class="!isFull ? 'teleplay-video-name' : ''">
            <view class="name">
              <view class="video-name">{{ episodeInfo.video_name
              ? episodeInfo.video_name
              : episodeInfo.name }}</view>
              <view class="sort">{{ `(${ sort }/${ episodeInfo.count })` }}</view>
            </view>

            <view class="select-sort" @click="handlePopup">
              选集<image style="height: 20rpx;" mode="widthFix" :src="OSSImgUrl(`arrow-top.png`)" />
            </view>
          </view>

        </view>
      </swiper-item>
    </swiper>
    <!-- 蒙层-弹层打开时禁止滑动 -->
    <view
      :class="showPopup || showPayPopup ? 'mask' : ''"
      @click="showPopup = false"
    ></view>
    <!-- 剧集弹窗 -->
    <EpisodeList
      :videoID="isLinkJumpVID ? isLinkJumpVID : episodeInfo.video_id"
      :showPopup.sync="showPopup"
      :sortTitle="sort"
      @updateEpisodeInfo="updateEpisodeInfo"
      :myVideoInfo="episodeInfo"
    ></EpisodeList>
    <!-- 充值弹出层 -->
    <PayPopup
      :videoInfo="episodeInfo"
      :currentVideoSort="sort"
      :showPopup.sync="showPayPopup"
      :IsUseAdPay="IsUseAdPay"
      page="video"
      :videoID="episodeInfo.video_id"
      @paySuccess="paySuccess"
    >
    </PayPopup>
    <!-- 提示更新弹窗 -->
    <u-modal
      :show="showModal"
      title="更新提醒"
      confirmColor="#f97632"
      closeOnClickOverlay
      @close="showModal = false"
      @confirm="showModal = false"
    >
      <view class="slot-content">
        <view class="modal-text">下一集视频未更新,更新后将第一时间提醒您</view>
      </view>
    </u-modal>
  </view>
  <u-loading-page
    v-else
    :loading="true"
    bg-color="#181818"
    loadingText="剧集正在拼命加载中~"
    iconSize="40"
  ></u-loading-page>
</template>

<script>
import MyVideo from "./components/MyVideo.vue";
import PayPopup from "@/components/PayPopup/index.vue";
import EpisodeList from "../media-player/components/EpisodeList.vue";
import {
  getApiEpisodeInfo,
  getApiEpisodeList,
  saveApiUserCollect,
  delApiUserCollect,
  getApiVideoList,
  dyGetEpisodeList,
  getDyAdEpisodeInfo,

  RewardedVideoAdShow,
  RewardedVideoAdEnd,
  RewardedVideoAdNoEnd,
  dyUnlockEpisode
} from "@/api/teleplay";
import { showMessage } from "@/utils/message";
import { getApiBalance } from "@/api/user";
import store from "@/store/index";
import { isShowPay, OSSImgUrl } from "@/utils/index";

let AdTimer = null;

let CacheRouterParams = {
  channel_id: uni.getStorageSync('channel_id'),
  plan_id: uni.getStorageSync('plan_id'),
};
let CacheEpisodeItem = null;
function CreateAdInstance(adUnitId){
  console.log("🚀 ~ CreateAdInstance ~ adUnitId:", adUnitId)
  const _this = this;
  this.TTAdInstance = tt.createRewardedVideoAd({
      adUnitId: adUnitId || this.DyAdId,
  });

  // 监听错误
  this.TTAdInstance.onError(handleError);
  // 监听视频播放完成
  this.TTAdInstance.onClose(handleClose);

  function handleError (err) {
    console.log("🚀 ~ this.TTAdInstance.onError ~ err:", err)
    uni.hideLoading();
    uni.showToast({
      title: "广告加载失败，稍后再试",
      icon: "none",
      duration: 1500,
      mask: true,
    })
    // switch (err.errCode) {
    //   case 1004:
    //     // 无合适的广告
    //     break;
    //   default:
    //   // 更多请参考错误码文档
    // }
  }

  async function handleClose(data) {
    console.log("🚀 ~ this.TTAdInstance.onClose ~ data:", data)
    console.log("当前剧集", _this.episodeInfo, CacheEpisodeItem)
    uni.hideLoading();

    if (data.isEnded) {
      console.log("观看了", data.count, "个视频");

      RewardedVideoAdEnd({
        channel_id: CacheRouterParams?.channel_id, 
        plan_id: CacheRouterParams?.plan_id, 
        eid: _this.eid
      }).then((res) => {
        console.log("埋点 RewardedVideoAdEnd 成功", res)
      }).catch((err) => {
        console.log("埋点 RewardedVideoAdEnd 失败", err)
      })

      const res = await dyUnlockEpisode({
        video_id: _this.episodeInfo?.video_id,
        sort: CacheEpisodeItem?.sort,
        eid: _this.eid,
        channel_id: CacheRouterParams?.channel_id,
        plan_id: CacheRouterParams?.plan_id,
        encrypted: CacheEpisodeItem?.encrypted
      })

      if(res?.code == 200){
        console.log("广告观看完毕解锁成功", res)
        _this.paySuccess();
        _this.AdBtnShow = false;
      }

    } else {
      console.log("未观看完视频");
      uni.showToast({
        title: "未观看完视频",
        icon: "none",
        duration: 1500,
        mask: true,
      })

      _this.AdTimeoutFunc(); // 重新倒计时
      RewardedVideoAdNoEnd({
        channel_id: CacheRouterParams?.channel_id, 
        plan_id: CacheRouterParams?.plan_id, 
        eid: _this.eid
      }).then((res) => {
        console.log("埋点 RewardedVideoAdNoEnd 成功", res)
      }).catch((err) => {
        console.log("埋点 RewardedVideoAdNoEnd 失败", err)
      })
    }
  }

  // 预加载资源
  this.TTAdInstance.load();
}

export default {
  options: { styleIsolation: "shared" },
  components: { EpisodeList, MyVideo, PayPopup },
  data() {
    return {
      isRecording: false, //禁止录屏
      isFull: false, //是否全屏
      isPlay: false, //播放状态
      showPopup: false, //剧集弹窗
      showPayPopup: false, //充值弹窗
      episodeInfo: {}, //剧集详情
      titleBarHeight: 0,
      windowHeight: 0,
      episodeList: [], //剧集列表
      currentIndex: 0, //轮播图页码
      sort: 1, //默认播放第一集
      flag: true, //节流阀
      isShowPayText: null, //付费内容文字
      timerId: null,
      showEpisodeList: null,
      eid: "", //用户id
      isLinkJump: false, //是否链接跳转
      isLinkJumpVID: null, //链接跳转的video-id
      duration: 200, //轮播图切换效果
      // controlDuration: false, //控制轮播图切换效果
      allArr: [], // 总数据
      showModal: false, //提示更新弹窗
      videoDown: false, //剧集下架

      
      IsUseAdPay: store.state.global.IsHasChannelType,
      DyAdId: null,
      TTAdInstance: null,
      AdBtnShow: false,
      IsChangingEpisodeInfo: false, // 等待集数信息更新
      AdTimeoutNum: 3,               // 当前秒数
      IsStopAdTimeout: false,       // 是否暂停广告倒计时
    };
  },
  // 打开分享面板时触发
  onShareAppMessage() {
    /**进入小程序携带的参数 */
    const launchData = uni.getLaunchOptionsSync();
    // 将参数转换成字符串携带分享在路径后
    const queryData = this.generateString(launchData.query);
    const share_id = launchData.query.share_id
      ? launchData.query.share_id
      : "3fbh0gcm03i517c772";
    return {
      path: `/pages_sub1/media-player/index?${queryData}`, // ?后面的参数会在转发页面打开时传入onLoad方法
      templateId: share_id, // templateId为开发者后台申请的分享 ID
      title: this.episodeInfo.video_name,
    };
  },
  async onLoad(params) {
    CacheRouterParams = {
      ...CacheRouterParams,
      ...params
    };
    console.log("🚀 ~ onLoad ~ params:", params)
    const { showEpisodeList, sort, paySort, video_id } = params || {}
    uni.setNavigationBarTitle({ title: `第${this?.sort || 0}集` });
    // 当不能充值页面回跳时重新获取剧集
    if (paySort) {
      this.sort = paySort;
      // this.episodeInfo.sort = this.sort
      // this.showPopup = true
      this.isShowPayText = 1;
      console.log("🚀 ~ onLoad ~ this.isShowPayText:", this.isShowPayText);
      this.currentIndex = paySort - 1;
    }
    // banner进入有剧集跳到对应集数
    if (this.episodeInfo.main_id) {
      this.currentIndex = this.episodeInfo.main_id - 1;
      this.sort = this.episodeInfo.main_id;
    }
    this.showEpisodeList = showEpisodeList;
    // -----------------------------------------------------------------------------------------------------------------
    // 如果是链接跳转小程序,从跳转参数中获取参数
    if (video_id) {
      this.isLinkJump = true;
      this.sort = sort ? sort : 1;
      this.currentIndex = sort - 1;
      this.isLinkJumpVID = video_id;
    }
  },
  async created() {
    this.IsUseAdPay = store.state.global.IsHasChannelType;
    // 获取用户id
    this.eid = uni.getStorageSync("userInfo").eid;
    this.episodeInfo = uni.getStorageSync("episodeInfo");
    // 是链接跳转播放
    if (this.isLinkJump) {
      // 获取剧集详情:this.isLinkJumpVID,跳转的videoID
      await this.getEpisodeList(this.isLinkJumpVID);
      await this.getEpisodeInfo(this.sort, this.isLinkJumpVID);
      await this.getVideoList(this.isLinkJumpVID);
    }
    // 不是链接跳转
    if (!this.isLinkJump) {
      this.sort = this.episodeInfo.sort ? this.episodeInfo.sort : this.sort;
      this.currentIndex = this.episodeInfo.sort ? this.episodeInfo.sort - 1 : 0;
      try {
        // 如果获取剧集和获取播放详情失败就返回首页
        await Promise.all([
          this.getEpisodeList(this.episodeInfo.video_id),
          this.getEpisodeInfo(this.sort, this.episodeInfo.video_id),
        ]);
      } catch (error) {
        // 显示黑色遮罩，防止白屏
        this.isRecording = true;
        this.videoDown = true;
        setTimeout(() => {
          uni.switchTab({ url: "pages/home/home" });
        }, 1500);
      }
    }

    await this.updateEpisodeList(this.sort);
  },
  onShow() {
    // 注册监听截屏函数
    // tt.onUserCaptureScreen();
    // 监听录屏
    // this.disableScreenRecord(tt.disableUserScreenRecord, tt.onUserScreenRecord)
  },
  onHide() {
    // 卸载监听录屏
    // this.disableScreenRecord(tt.enableUserScreenRecord, tt.offUserScreenRecord)
    // 卸载监听截屏函数
    // tt.offUserCaptureScreen();
  },
  methods: {
    OSSImgUrl: OSSImgUrl,

    handleStopAdClick(){
      this.IsStopAdTimeout = true; // 暂停倒计时

      AdTimer && clearInterval(AdTimer);
      AdTimer = null;
    },
    AdTimeoutFunc(){
      AdTimer && clearInterval(AdTimer);
      this.AdTimeoutNum = 3;
      this.IsStopAdTimeout = false;

      AdTimer = setInterval(() => {
        this.AdTimeoutNum -= 1;
        if(this.AdTimeoutNum <= 0){
          AdTimer && clearInterval(AdTimer);
          AdTimer = null;

          this.handleAdClick(); // 看广告
        }
      }, 1000)
    },
    handleAdClick(){
      uni.showLoading({
        title: '加载中',
        mask: true,
      });

      AdTimer && clearInterval(AdTimer); // 清除计时器

      this?.TTAdInstance?.show().then(() => {
        console.log("显示广告成功");
        RewardedVideoAdShow({
          channel_id: CacheRouterParams?.channel_id, 
          plan_id: CacheRouterParams?.plan_id, 
          eid: this.eid
        }).then((res) => {
          console.log("埋点 RewardedVideoAdShow 成功", res)
        }).catch((err) => {
          console.log("埋点 RewardedVideoAdShow 失败", err)
        })
      }).catch((err) => {
        console.log("广告加载失败，请稍后再试")
        uni.hideLoading()

        uni.showToast({
          title: "广告加载失败，请稍后再试",
          icon: "none",
          duration: 1500,
          mask: true,
        })
      })
    },
    // 1.选集列表切换播放
    async updateEpisodeInfo(sort, showPayText) {
      AdTimer && clearInterval(AdTimer); // 清除定时器
      AdTimer = null;

      // 在循环列表中找到选集的当前项
      CacheEpisodeItem = this?.episodeList?.find((item) => item?.sort === sort);
      console.log("🚀 获取剧集信息updateEpisodeInfo:", CacheEpisodeItem)
      this.updateEpisodeList(sort);
      // this.controlDuration = true;
      this.duration = 0;
      this.isShowPayText = showPayText;
     
      // 轮播图下标从0开始,赋值时需减一
      if (sort) {
        this.currentIndex = sort - 1;
        this.sort = sort;

        // 信息获取，同时校验
        this.getEpisodeInfo(sort, this.episodeInfo.video_id);
      }
      // 关闭弹窗
      this.showPopup = false;
      // 允许滑动
      this.catchtouchmove = true;
      // if (CacheEpisodeItem === undefined) {
      //   // 列表还没生成 不会触发滑动事件
      //   this.controlDuration = false;
      // }
    },
    // 2.获取剧集详情:sort第几集 video_menu_id:剧集id
    async getEpisodeInfo(sort, video_id) {
      CacheEpisodeItem = this?.episodeList?.find((item) => item?.sort === sort);
      console.log("🚀 获取剧集信息getEpisodeInfo:", CacheEpisodeItem)
      try {
        const { data, code, msg } = await (this.DyAdId ? getDyAdEpisodeInfo : getApiEpisodeInfo)(
          video_id,
          sort,
          this.eid
        );

        if (msg === "need_ad") {
          // 看广告
          this.AdBtnShow = true;
          this.isShowPayText = 1;
          this.episodeInfo.file_url = "";
          this.episodeInfo.sort = this.sort;
          console.log("🚀 ~ getEpisodeInfo ~ this.AdBtnShow:", this.AdBtnShow)

          this.AdTimeoutFunc(); //广告倒计时
          return new Promise((resolve, reject) => reject(new Error(msg)));
        }

        // 如果获取剧集失败跳转首页
        if (msg === "invalid video_id") {
          showMessage("视频ID缺失, 请稍后重试~");
          setTimeout(() => {
            tt.switchTab({ url: "/pages/home/home" });
          }, 1000);
          return;
        }
        // 如果剧集未上架弹窗提示
        if (code === 30006) {
          uni.showToast({
            title: "该视频未上架,可先观看其他剧集~",
            icon: "none",
            duration: 1500,
          });
          // 获取剧集失败不播放视频
          this.episodeInfo.file_url = "";
          return new Promise((resolve, reject) => reject(new Error(msg)));
        }
        // 储存用户余额
        // 将VIP时间也重新赋值
        const { vip_time } = uni.getStorageSync("balance");
        uni.setStorageSync("balance", {
          balance: data.balance || 0,
          give_balance: data.give_balance || 0,
          vip_time: vip_time || 0,
        });

        // 储存过期时间
        const expire_time = data.expire_time - Date.now();
        // this.episodeInfo = Object.assign({}, this.episodeInfo, data)

        this.episodeInfo =
          this.episodeInfo && typeof this.episodeInfo === "object"
            ? { ...this.episodeInfo, ...(data || {}) }
            : data && typeof data === "object"
            ? { ...data }
            : {};

        // 视频过期重新发送请求
        if (expire_time !== 0 && this.flag) {
          this.flag = false;
          this.timerId = setTimeout(async () => {
            const { data } = await (this.DyAdId ? getDyAdEpisodeInfo : getApiEpisodeInfo)(video_id, sort, this.eid);
            this.episodeInfo =
              this.episodeInfo && typeof this.episodeInfo === "object"
                ? { ...this.episodeInfo, ...(data || {}) }
                : data && typeof data === "object"
                ? { ...data }
                : {};
            this.flag = true;
          }, expire_time);
        }
      } catch (error) {
        console.log("🚀 ~ getEpisodeInfo ~ error:", error);
        if(this.DyAdId){
          
        } else {
          const showPay = isShowPay(
            () => {
              // ios可以支付
              this.showPayPopup = true;
              this.catchtouchmove = true;
              this.isShowPayText = 1;
              
              this.episodeInfo.file_url = "";
              this.episodeInfo.sort = this.sort;
              // 当余额不足时显示付费文字
              if (error.message === "not_balance") {
                this.isShowPayText = 1;
              }
              new Promise((resolve, reject) => {
                reject(error);
              });
            },
            () => {
              // 跳转ios不许支付页面
              // 当余额不足时显示付费文字
              if (error.message === "not_balance") {
                this.isShowPayText = 1;
              }
              // 如果不是从ios不能支付页面跳转就跳转页面
              if (!this.iosPage) {
                uni.navigateTo({
                  url: `/pages_sub1/pay-recharge/index?sort=${sort}&videoID=${this.episodeInfo.video_id}`,
                });
              }
              this.iosPage = false;
            }
          );

          if (!showPay) {
            this.showModal = true;
            this.currentIndex = this.currentIndex - 1;
            // this.sort = this.sort - 1
            // this.getEpisodeInfo(this.sort, this.episodeInfo.video_id)
            return;
          }
        }
      }
    },
    // 3.滑动切换视频
    async handleChangeVideo({ target }) {
      this.IsChangingEpisodeInfo = true;
      AdTimer && clearInterval(AdTimer); // 清除定时器
      AdTimer = null;


      // 重新获取循环列表
      this.updateEpisodeList(this.sort);

      this.episodeInfo.file_url = null;
      this.currentIndex = target.current;
      this.sort = target.current + 1;

      // 如果从收费集往上走,把消费文字提示隐藏
      if (this.isShowPayText === 1 && target.current < this.sort) {
        this.isShowPayText = null;
        this.currentIndex = this.currentIndex;
      }
      try {
        await this.getEpisodeInfo(
          target.current + 1,
          this.episodeInfo.video_id
        );
        this.IsChangingEpisodeInfo = false;
      } catch (error) {
        this.episodeInfo.file_url = null;
      }
    },
    // 轮播图循环列表优化
    updateEpisodeList(sort) {
      const newArr = this.allArr.filter((item) => item.sort <= sort + 3);
      this.episodeList = newArr;
    },
    // 4.返回上一页
    leftClick() {
      // 储存最近观看的剧和剧集
      uni.setStorageSync("recentVideo", this.episodeInfo);
      let pages = getCurrentPages(); //获取页面栈
      let prevPage = pages[pages.length - 2]; //上一个页面
      if (!prevPage) {
        // 如果是链接跳转没有上一个页面栈则返回主页面
        uni.switchTab({ url: "/pages/home/home" });
        return;
      }
      uni.navigateBack({ delta: 1 });
    },
    // 5.充值成功
    async paySuccess() {
      console.log("充值成功回调");

      // 重新获取余额
      this.getBalance();
      // 重新获取剧集
      await this.getEpisodeInfo(this.sort, this.episodeInfo.video_id);
      this.isShowPayText = null;
    },
    // 获取用户余额
    async getBalance() {
      const eid = uni.getStorageSync("userInfo").eid;
      const {
        data: { balance, give_balance, vip_time },
      } = await getApiBalance(eid);
      console.log("🚀 ~ 用户余额获取:", balance, give_balance, vip_time);
      uni.setStorageSync("balance", {
        balance: balance ? balance : 0,
        give_balance: give_balance ? give_balance : 0,
        vip_time: vip_time ? vip_time : 0,
      });
    },
    // 获取剧集列表
    async getEpisodeList(video_id) {
      console.log("🚀 ~ getEpisodeList ~ this.IsUseAdPay:", this.IsUseAdPay, video_id)
      if(this.IsUseAdPay === 1){
        const {
          data: { list, ad_id },
          code,
          msg,
        } = await dyGetEpisodeList({
          video_id, 
          pn: 1,
          ps: 1000, 
          eid: this.eid
        });
        if (code === 500) {
          // 如果没有获取到剧集弹窗提示
          uni.showToast({
            title: "该剧暂无剧集,可先观看其他短剧~",
            icon: "none",
            duration: 1500,
          });
          return new Promise((resolve, reject) => reject(new Error(msg)));
        }
        // 全部数据，存储便于后续截取赋值到展示数组
        this.allArr = Array.isArray(list) && list.length ? list : [];
        if(ad_id){
          this.DyAdId = ad_id;
          CreateAdInstance.call(this, ad_id)
        }
      } else {
        const {
          data: { list },
          code,
          msg,
        } = await getApiEpisodeList(video_id, 1, 1000, this.eid);
        if (code === 500) {
          // 如果没有获取到剧集弹窗提示
          uni.showToast({
            title: "该剧暂无剧集,可先观看其他短剧~",
            icon: "none",
            duration: 1500,
          });
          return new Promise((resolve, reject) => reject(new Error(msg)));
        }
        // 全部数据，存储便于后续截取赋值到展示数组
        this.allArr = Array.isArray(list) && list.length ? list : [];
      }
    },

    // 加入追剧列表
    async setUserCollect() {
      if (!this.eid) return;
      //is_collect: 1已追剧 0未追剧
      if (this.episodeInfo.is_collect === 1) {
        // 如果当前收藏状态则取消收藏
        const { code } = await delApiUserCollect(
          this.episodeInfo.video_id,
          this.eid
        );
        if (code === 200) {
          showMessage("取消追剧成功~");
          this.episodeInfo.is_collect = 0;
        }
        return;
      }
      // 添加追剧-收藏短剧
      const { code } = await saveApiUserCollect(
        this.episodeInfo.video_id,
        this.eid
      );
      if (code === 200) {
        showMessage("添加追剧成功~");
        this.episodeInfo.is_collect = 1;
      }
    },
    // 控制弹出层
    handlePopup() {
      // console.log(id)
      // 暂停播放=>调用子组件的暂停方法
      this.showPopup = true;
      this.catchtouchmove = false;
    },
    /**
     * 禁止录屏、截屏
     * @param {监听安卓录屏动作} handleAndroidScreenRecord
     * @param {*监听ios录屏动作} handleIosScreenRecord
     */
    disableScreenRecord(handleAndroidScreenRecord, handleIosScreenRecord) {
      // 监听录屏
      uni.getSystemInfo({
        success: (e) => {
          if (e.platform == "android") {
            // 程序在安卓手机上 禁止截屏/录屏(注意：禁止后录屏动作还是会进行，但录屏后的视频是黑屏的)
            handleAndroidScreenRecord();
          } else {
            // 小程序IOS手机
            const callback = (res) => {
              if (res.state === "start") {
                this.isRecording = true;
                // 开始录屏
              } else if (res.state === "stop") {
                // 取消录屏
                this.isRecording = false;
              }
            };
            handleIosScreenRecord(callback);
          }
        },
      });
    },
    // 获取渠道进入时的短剧信息
    async getVideoList(video_id) {
      const { data } = await getApiVideoList(1, 1, video_id);
      this.episodeInfo = Object.assign(this.episodeInfo, data.list[0]);
    },
    // 拼接onLaunchquery参数
    generateString(obj) {
      // 从请求默认对象中获取
      const aid = store.state.user.defaultParams.aid;
      // 如果进入小程序时没有携带参数则使用默认对象
      if (Object.keys(obj).length <= 0) {
        obj = {
          channel_id: uni.getStorageSync("channel_id") || 0,
          video_id: this.episodeInfo.video_id,
          sort: 1,
          form: 99,
          aid,
          share_id: "3fbh0gcm03i517c772",
        };
      }
      const keys = Object.keys(obj);
      const values = Object.values(obj);
      const pairs = keys.map((key, index) => `${key}=${values[index]}`);
      const stringified = pairs.join("&");
      return stringified; // 输出：&sort=1&channel_id=211
    },
    // 截取部分列表
    filterList() {
      // 当ios不可以充值时||审核状态时||需要渠道ID但是没有渠道ID时,展示部分列表
      // 如果是审核模式就筛选掉VIP剧集
      const isShow = isShowPay();
      if (!isShow) {
        this.allArr = this.allArr.filter((item) => item.is_vip === 0);
      }
    },
  },
  watch: {
    // 监听集数动态修改状态栏
    sort: {
      handler: function () {
        uni.setNavigationBarTitle({ title: `第${this.sort}集` });
      },
    },
  },
  beforeDestroy() {
    // 剧集没有下架的情况记录追剧记录
    if (!this.videoDown) {
      uni.setStorageSync("recentVideo", this.episodeInfo);
    }

    (this?.TTAdInstance?.destroy) && this?.TTAdInstance?.destroy();

    // 在页面销毁之前清除延时器
    if (this.timerId) {
      clearTimeout(this.timerId);
    }
  },
};
</script>

<style lang="scss" scoped>

.teleplay-video-name{
  position: absolute;
  bottom: 120rpx;
  left: 20rpx;
  z-index: 99;
  font-size: 30rpx;
  color: #fff;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 60rpx;
  height: 60rpx;
  
  box-sizing: border-box;
  padding: 10rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .name{
    display: flex;
    align-items: center;
    justify-content: center;

    .video-name{
      max-width: 340rpx;
      white-space: nowrap; /* 禁止换行 */
      overflow: hidden; /* 超出部分隐藏 */
      text-overflow: ellipsis; /* 超出部分显示省略号 */
    }

    .sort{
      margin-left: 10rpx;
    }

  }

  .select-sort{
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 40rpx;

    image {
      width: 20rpx;
      height: 20rpx;
      margin-left: 5rpx;
    }
  }
}

.ad-btn{
  width: 400rpx;
  border-radius: 8px;

  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: linear-gradient(to bottom, #FFC9A0, #fd832c, #FE6B01);
}

.ad-tip-wrapper{
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  background: rgba(0, 0, 0, 0.5);
  border-radius: 30%;

  text {
    color: #fff;
    font-size: 30rpx;
    white-space: nowrap;

    &:first-child {
      margin-bottom: 10rpx;
    }
  }
}

.ad-thumb-wrapper{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 50;
}

.ad-timeout-wrapper{
  position: absolute;
  bottom: 190rpx;
  right: 10rpx;
  display: inline-flex;
  justify-content: space-between;

  .ad-timeout-btn {
    border-radius: 12rpx;
    box-sizing: border-box;
    padding: 15rpx 20rpx;
    font-size: 28rpx;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(to bottom, #FFC9A0, #fd832c, #FE6B01);
  }

  .ad-btn-close{
    color: #fff;
    background-color: #746c68;
    font-weight: bold;
    margin-left: 10rpx;

    border-radius: 12rpx;
    box-sizing: border-box;
    padding: 6rpx 16rpx;
    font-size: 44rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

::v-deep {
  .u-cell__body {
    padding: 0 !important;
  }
}

.media-player-page {
  .recording-mask {
    background: #000;
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: 99999;
    top: 0;
    left: 0;
  }

  .mask {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100vw;
    height: 35vh;
  }

  ::v-deep {
    .xg-video {
      height: 100%;
      width: 100%;
    }

    .u-navbar__content {
      height: 20rpx !important;
      background-color: rgba(255, 255, 255, 0) !important;
      position: relative;
      top: 40rpx;
      color: #fff !important;
    }
  }

  .veplayer-page {
    position: fixed;
    left: 0;
    width: 100%;
    height: 100vh;
    padding-bottom: 40rpx;
    box-sizing: border-box;
    background-color: black;

    .sidebar {
      position: absolute;
      right: 20rpx;
      bottom: 30%;
      display: flex;
      flex-direction: column;
      align-items: center;

      width: 120rpx;

      & > view, & > button {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 0;
        background: transparent;
        
        &::after {
          border: 0;
        }

        &:not(:last-child){
          margin-bottom: 30rpx;
        }

        image {
          width: 100%;
        }

        .txt {
          color: #fff;
          font-size: 30rpx;
          line-height: initial;
          margin-top: 10rpx;
        }
      }
    }

    .hidden {
      display: none;
    }

    .full-screen {
      position: absolute;
      bottom: 120rpx;
      right: 5rpx;
      z-index: 99;
      width: 50rpx;
      height: 48rpx;
      padding: 20rpx;
    }

    .pay-text {
      width: 85%;
      position: absolute;
      top: 40%;
      left: 47%;
      transform: translate(-41%, -50%);
      font-size: 34rpx;
      color: #fff;
    }

    .episode-list {
      width: 750rpx;
      height: 900rpx;

      .scroll-Y {
        height: 1000rpx;
      }
    }
  }
}

::v-deep {
  .u-line {
    border-color: #fff !important;
  }
}
</style>
